using AudioStudio;
using AudioStudio.Tools;
using GTATools.AssetImport;
using HybridCLR.Editor;
using HybridCLR.Editor.Installer;
using System.Collections.Generic;
using System.IO;
using System.Text;
using TMPro;
using UnityEditor;
using UnityEngine;

using Yoozoo.Editor.Utils;
using Yoozoo.Gameplay.Managers.ResourceManagerV2.Editor;
using Yoozoo.Gta.ProjBuilder;
using Yoozoo.Managers.ResourceManagement;
using Yoozoo.Managers.ResourceManagerV2.Editor.ResourceTools;
using Yoozoo.Managers.ResourceManagerV2.Framework;
using LogType = UnityEngine.LogType;

public static class  JenkinsBuildSupport
{
    
    [MenuItem("Tools/Jenkins Support/Build With Auto Analysis")]
    public static void BuildResourcesAuto()
    {
        
        UnityEngine.Application.SetStackTraceLogType(LogType.Log,StackTraceLogType.None);
        UnityEngine.Application.SetStackTraceLogType(LogType.Warning,StackTraceLogType.None);
        // Resources
        BuildResources.RunAnalysisByLatestConfig();
        AssetDatabase.Refresh();
        BuildResources.Run();

        AssetDatabase.Refresh();
        // EditorUtility.DisplayDialog("打包完成", "资源包完成！", "明白");
        
        UnityEngine.Application.SetStackTraceLogType(LogType.Log,StackTraceLogType.ScriptOnly);
        UnityEngine.Application.SetStackTraceLogType(LogType.Warning,StackTraceLogType.ScriptOnly);
    }

    [MenuItem("Tools/Jenkins Support/GetChannelConfigPath")]
    public static void GetChannelConfigPath()
    {
        string path = TypeUtility.GetConfigurationPath<ChannelConfigPathAttribute>();
        ChannelConfig config = AssetDatabase.LoadAssetAtPath<ChannelConfig>(path);
        if (config==null)
        {
            EditorUtility.DisplayDialog("information", "需要配置channelconfig文件", "Ok");
        }
    }
    
    [MenuItem("Tools/Jenkins Support/Build Lua only")]
    public static void BuildLuaAuto()
    {
        Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
        Application.SetStackTraceLogType(LogType.Warning, StackTraceLogType.None);
        Yoozoo.Managers.ResourceManagement.BuildPlayer.SetGraphicsAPIs();

        //包内资源大小（0：不带资源，-1：所有资源
        int packageResourceType = -2;
        bool cryptBundleName = true;
        bool isFirstPackage = true;

        Plugins.ManuallyReload.ManuallyReloadSetting.Instance.IsEnableManuallyReload = false;

        SubPackageTool.SetAppConfig(isFirstPackage);
        ModifyResourceSettings(cryptBundleName);
        
        GtaVersionProcess.FirstPackageSizeLimit = packageResourceType;
        BuildResources.BuildLua();

        Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.ScriptOnly);
        Application.SetStackTraceLogType(LogType.Warning, StackTraceLogType.ScriptOnly);
    }

    /// <summary>
    /// 构建Lua
    /// </summary>
    public static void BuildLua()
    {
        UnityEngine.Debug.Log("JenkinsBuildSupport.BuildLua Begin");
        Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
        Application.SetStackTraceLogType(LogType.Warning, StackTraceLogType.None);
        
        UnityEngine.Debug.Log("SetGraphicsAPIs Begin");
        Yoozoo.Managers.ResourceManagement.BuildPlayer.SetGraphicsAPIs();

        //包内资源大小（0：不带资源，-1：所有资源
        int packageResourceType = int.Parse(GetCMDLineArg("-packageResourceType"));
        //1.0.0.2554327
        string version = GetCMDLineArg("-resVersion");
        string abPath = GetCMDLineArg("-abPath");
        // "${WORKSPACE_DIR}/Patches/${CHANNEL}
        // /d/gtaClient/Workspace/workspace/gta_pc_for_S1/Patches/S1
        string patchFullPath = GetCMDLineArg("-patchFullPath");
        bool cryptBundleName = GetCMDLineArg("-crypt") == "true";
        bool isFirstPackage = GetCMDLineArg("-firstPackage") == "true";

        Plugins.ManuallyReload.ManuallyReloadSetting.Instance.IsEnableManuallyReload = false;

        SubPackageTool.SetAppConfig(isFirstPackage);
        ModifyResourceSettings(cryptBundleName);

        string[] versionParts = version.Split('.');
        int lastIndexOfDot = version.LastIndexOf('.');
        PlayerSettings.bundleVersion = version.Substring(0, lastIndexOfDot);
        string resInternalVersion = versionParts[versionParts.Length - 1];

        GtaVersionProcess.FirstPackageSizeLimit = packageResourceType;
        UnityEngine.Debug.Log($"packageResourceType = {packageResourceType}, FirstPackageSizeLimit = {GtaVersionProcess.FirstPackageSizeLimit}");

        var platform = Platform.FollowProject;
#if UNITY_IOS
        platform = Platform.IOS;
#elif UNITY_ANDROID
        platform = Platform.Android;
#elif UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
        platform = Platform.Windows64;
#else
#endif
        UnityEngine.Debug.Log("BuildResources.BuildLua Begin");
        BuildResources.BuildLua(resInternalVersion, platform, abPath, patchFullPath);
        UnityEngine.Debug.Log("BuildResources.BuildLua End");

        UnityEngine.Debug.Log("AssetDatabase.Refresh Begin");
        AssetDatabase.Refresh();
        UnityEngine.Debug.Log("AssetDatabase.Refresh End");

        Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.ScriptOnly);
        Application.SetStackTraceLogType(LogType.Warning, StackTraceLogType.ScriptOnly);
        
        UnityEngine.Debug.Log("JenkinsBuildSupport.BuildLua End");
    }

    /// <summary>
    /// 构建资源
    /// </summary>
    public static void BuildAssetBundle()
    {
        Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
        Application.SetStackTraceLogType(LogType.Warning, StackTraceLogType.None);
        Yoozoo.Managers.ResourceManagement.BuildPlayer.SetGraphicsAPIs();
        EditorSettings.cacheServerMode = CacheServerMode.Disabled;
        EditorSettings.cacheServerEnableDownload = false;
        EditorSettings.cacheServerEnableUpload = false;

        //包内资源大小（0：不带资源，-1：所有资源
        int packageResourceType = int.Parse(GetCMDLineArg("-packageResourceType"));
        //1.3.2.2554327
        string version = GetCMDLineArg("-resVersion");
        string abPath = GetCMDLineArg("-abPath");
        string patchFullPath = GetCMDLineArg("-patchFullPath");
        bool forceRebuild = GetCMDLineArg("-forceRebuild") == "true";
        bool cryptBundleName = GetCMDLineArg("-crypt") == "true";
        bool isFirstPackage = GetCMDLineArg("-firstPackage") == "true";
        //是否热更C#
        bool isHybridClr = GetCMDLineArg("-isHybridClr") == "true";
        // 开启资源更新
        bool isUpdateResource = GetCMDLineArg("-updateResource") == "true";

        UnityEngine.Debug.Log("isHybridClr = " + isHybridClr);

        Plugins.ManuallyReload.ManuallyReloadSetting.Instance.IsEnableManuallyReload = false;

        SubPackageTool.SetAppConfig(isFirstPackage);
        ModifyResourceSettings(cryptBundleName);

        if (isUpdateResource)
        {
            // 开启热更，需要Full
            SetOutputFullSelected(true);
        }
        else
        {
            // 不开启热更，资源都在Packed目录下，不要Full
            SetOutputFullSelected(false);
        }

        // 清理模型里的材质
        DelModelStandardMaterial.ReimportModels();

        // 清理动态的TMP_FontAsset
        var tmpPreBuildProcessor = new TMP_PreBuildProcessor();
        tmpPreBuildProcessor.OnPreprocessBuild(null);

        string[] versionParts = version.Split('.');
        int lastIndexOfDot = version.LastIndexOf('.');
        PlayerSettings.bundleVersion = version.Substring(0, lastIndexOfDot);
        string resInternalVersion = versionParts[versionParts.Length - 1];

        GtaVersionProcess.FirstPackageSizeLimit = packageResourceType;
        UnityEngine.Debug.Log($"packageResourceType = {packageResourceType}, FirstPackageSizeLimit = {GtaVersionProcess.FirstPackageSizeLimit}");

        // var checker = new AssetUpdateChecker();
        // checker.Load();
        // checker.Dump($"{abPath}/Working/{version}.assets.txt");

        var platform = Platform.FollowProject;
#if UNITY_IOS
        platform = Platform.IOS;
#elif UNITY_ANDROID
        platform = Platform.Android;
#elif UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
        platform = Platform.Windows64;
#else
#endif
        BuildResources.Run(resInternalVersion, forceRebuild, platform, abPath, patchFullPath, null);

        AssetDatabase.Refresh();

        Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.ScriptOnly);
        Application.SetStackTraceLogType(LogType.Warning, StackTraceLogType.ScriptOnly);

        // /这里检查脚本是否有更新，有更新的话写入BuildReport目录
        // BuildResources.Run会清空abPath，所以这里要放到后面执行
        var versionNoDot = version.Replace(".", "_");
        string updatedScriptsLogPath = $"{abPath}/BuildReport/{versionNoDot}/UpdatedScripts.txt";
        string allInfoScriptsLogPath = $"{abPath}/BuildReport/{versionNoDot}/AllUpdatedScripts.txt";
        CheckAssemblyUpdated(updatedScriptsLogPath, allInfoScriptsLogPath);
    }

    /// <summary>
    /// 检查脚本是否有修改，如果有的话，将修改的脚本列表写入到BuildReport目录作为标记
    /// </summary>
    /// <param name="aotInfoOutputPath"></param>
    /// <param name="allInfoOutputPath"></param>
    private static void CheckAssemblyUpdated(string aotInfoOutputPath, string allInfoOutputPath)
    {
        var checker = new AssetUpdateChecker();
        var aotInfoOutput = new StringBuilder();
        var allInfoOutput = new StringBuilder();
        checker.SetOutput(aotInfoOutput, allInfoOutput);

        string directory = Path.GetDirectoryName(allInfoOutputPath);
        if (!Directory.Exists(directory))
            Directory.CreateDirectory(directory);

        if (checker.IsAssemblyUpdated())
        {
            directory = Path.GetDirectoryName(aotInfoOutputPath);
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);
            UnityEngine.Debug.LogFormat("Write to: {0}", aotInfoOutputPath);

            File.WriteAllText(aotInfoOutputPath, aotInfoOutput.ToString());
        }
        
        UnityEngine.Debug.LogFormat("Write to: {0}", allInfoOutputPath);
        File.WriteAllText(allInfoOutputPath, allInfoOutput.ToString());
    }

    public static void ModifyResourceSettings(bool cryptBundleName)
    {
        EditorResourceSettings.EnsureLoadConfig();
        EditorResourceSettings.CryptBundleName = cryptBundleName;
        EditorResourceSettings.SaveConfig();
        EditorResourceSettings.LoadConfig();
    }

    public static void SetForceRebuildAssetBundleSelected(bool forceRebuild)
    {
        var controller = new ResourceBuilderController();
        if (controller.Load(false))
        {
            controller.ForceRebuildAssetBundleSelected = forceRebuild;
            controller.Save();
        }
    }

    public static void SetOutputFullSelected(bool isOutputFullSelected)
    {
        var controller = new ResourceBuilderController();
        if (controller.Load(false))
        {
            controller.OutputFullSelected = isOutputFullSelected;
            controller.Save();
        }
    }

    /// <summary>
    /// 构建安装包
    /// </summary>
    public static void BuildPlayer()
    {
        UnityEngine.Debug.Log("BuildPlayer");

        string resourceVersion = GetCMDLineArg("-resVersion"); //资源版本号

        int packageResourceType = int.Parse(GetCMDLineArg("-packageResourceType")); //包内资源大小（0：不带资源，-1：所有资源

        string abPath = GetCMDLineArg("-abPath"); //ab包路径
        string packagePath = GetCMDLineArg("-packagePath"); //安装包路径
        bool isLog = GetCMDLineArg("-log") == "true" ? true : false; //是否打开日志
        bool isDevelopmentBuild = GetCMDLineArg("-isDevelopmentBuild") == "true" ? true : false; //是否是开发模式
        bool isDeepMode = GetCMDLineArg("-isDeepMode") == "true" ? true : false; //是否是开发模式
        bool isAutoProfiler = GetCMDLineArg("-isAutoProfiler") == "true" ? true : false; //是否是开发模式
        bool isUWALauncher = GetCMDLineArg("-UWA_Launcher") == "true"; // 是否打开UWA
        bool isUprProfiler = GetCMDLineArg("-isUprProfiler") == "true"; // 是否打开UPR
        string serverVersionUrl = GetCMDLineArg("-serverVersionUrl"); //versionUrl路径
        string channel = GetCMDLineArg("-channel"); //渠道
        string bundleVersion = GetCMDLineArg("-appVersion"); //版本号 bundleVersion=1.0.0.f1a4a3502
        string bundleVersionCode = GetCMDLineArg("-bundleVersionCode"); //bundleVersionCode
        bool isGT = GetCMDLineArg("-GT") == "true"; //GT
        bool isYZPD = GetCMDLineArg("-YZPD") == "true"; //YZPD
        bool isUpdateResource = GetCMDLineArg("-updateResource") == "true"; // 开启资源更新
        bool isExportProject = GetCMDLineArg("-exportProject") == "true"; //是否导出工程
        string subPackage = GetCMDLineArg("-subPackage"); // full(完整包）, pve（仅pve模式），rpg（仅rpg模式），其他 = full
        bool isEventTrace = GetCMDLineArg("-EventTrace") == "true"; // 是否发送统计数据
        string architecture = GetCMDLineArg("-arch"); // 安卓架构, all, arm64, armv7, split
        bool isFirstPackage = GetCMDLineArg("-isFirstPackage") == "true"; //是否边玩边下模式
        bool isHybridClr = GetCMDLineArg("-isHybridClr") == "true"; //是否热更C#

        StreamingAssetBuild.ClearStreamingAssets();

#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
        UnityEngine.Debug.Log("Use StreamingAssetsProcessor");

        // Android和iOS平台，不把资源直接复制到StreamingAssets目录，而是在构建完成后再复制
        // StreamingAssetsProcessor 实现了 IPostprocessBuildWithReport 和 IPostGenerateGradleAndroidProject 接口，会在构建完成后执行
        PackageResourceType resourceType;

        if (packageResourceType > 0)
        {
            resourceType = PackageResourceType.Full;
        }
        else
        {
            resourceType = (PackageResourceType)packageResourceType;
        }
        StreamingAssetsProcessor.Settings = new StreamingAssetsProcessor.StreamingAssetsSettings()
        {
            PackageResourceType = resourceType,
            OutputPath = abPath,
            Version = bundleVersion.Replace('.', '_'),
        };
#else
        UnityEngine.Debug.Log("CopyToStreamingAssets");
        // 直接复制资源到StreamingAssets目录
        PackageResourceType resourceType = (PackageResourceType)packageResourceType;
        if (resourceType == PackageResourceType.Zero)
        {
            StreamingAssetBuild.GenerateStreamingAssetWithoutAssetBundles();
        }
        else
        {
            if (!string.IsNullOrEmpty(resourceVersion))
            {
                Debug.Log("Copying latest version resource files begin!");
                StreamingAssetBuild.GenerateStreamingAssetByVersion(abPath, resourceVersion.Replace('.', '_'));
                Debug.Log("Copying latest version resource files success!");
            }
            else
            {
                StreamingAssetBuild.GenerateStreamingAssetByLatest(abPath);
            }
        }
#endif

        // bundleVersion = 1.0.0.f1a4a3502
        bundleVersion = bundleVersion.Substring(0, bundleVersion.LastIndexOf('.'));

        Debug.Log("Build begin");
        using (var setup = new DefineSymbolSetup())
        {
            setup.UpdateDefineSymbol("GT", isGT);
            setup.UpdateDefineSymbol("YZPD", isYZPD);
            setup.UpdateDefineSymbol("UWA", isUWALauncher);
            if (isUWALauncher)
            {
                setup.UpdateDefineSymbol("ENABLE_UWA_SDK", true);
            }
            else
            {
                setup.UpdateDefineSymbol("DISABLE_UWA_SDK", true);
            }
            setup.UpdateDefineSymbol("EventTrace", isEventTrace);
            setup.UpdateDefineSymbol("ENABLE_HYBRID_CLR", isHybridClr);
            setup.UpdateDefineSymbol("DEBUG", isLog);
            setup.UpdateDefineSymbol("ENABLE_LOG", isLog);
            if (!isLog)
            {
                //开启error和warning的日志打印
                setup.UpdateDefineSymbol("ENABLE_WARNING_AND_ABOVE_LOG", true);
            }

            // 暂时没有单独的选项控制OnGUI(), 用 isLog 进行控制
            setup.UpdateDefineSymbol("ASTAR_NO_GUI", !isLog);
            setup.UpdateDefineSymbol("ENABLE_ONGUI_RUNTIME", isLog);

            //加xlua编译宏
            setup.UpdateDefineSymbol("XLua", true);

            // 不开启UPR的时候，启用 NO_PACKAGE， UPRTools/Scripts/PackageLoad
            setup.UpdateDefineSymbol("NO_PACKAGE", !isUprProfiler);
            if (!isUprProfiler)
            {
                // 不开启UPR的时候，移除USE_LUA,UPR_LUA_PROFILER
                setup.UpdateDefineSymbol("USE_LUA", false);
                setup.UpdateDefineSymbol("UPR_LUA_PROFILER", false);
            }
        }

        if (!isUprProfiler)
        {
            // 不开启UPR的时候，所有选项关闭，不要注入代码了
            // var setting = UPRToolSetting.Instance;
            // setting.enableMonoProfiler = false;
            // setting.loadScene = false;
            // setting.loadAsset = false;
            // setting.loadAssetBundle = false;
            // setting.instantiate = false;
            // setting.enableLuaProfiler = false;
        }

        if (!isUWALauncher)
        {
            if (Directory.Exists("Assets/UWA/UWA_SDK/Runtime/Resources"))
            {
                Directory.Delete("Assets/UWA/UWA_SDK/Runtime/Resources", true);
            }
        }
        
        Plugins.ManuallyReload.ManuallyReloadSetting.Instance.IsEnableManuallyReload = false;

        UnityEngine.Debug.Log("isHybridClr = " + isHybridClr);
        if (isHybridClr)
        {
            // 入口场景设为Entry
            EditorBuildSettings.scenes = new EditorBuildSettingsScene[]
            {
                new EditorBuildSettingsScene("Assets/Scenes/Entry.unity", true)
            };

            // 开启HybridCLR
            HybridCLR.Editor.SettingsUtil.Enable = true;
        }
        else
        {
            // 入口场景设为Main
            EditorBuildSettings.scenes = new EditorBuildSettingsScene[]
            {
                new EditorBuildSettingsScene("Assets/Scenes/Main.unity", true)
            };
            
            // 关闭HybridCLR
            HybridCLR.Editor.SettingsUtil.Enable = false;
        }
        
        var arch = GetArchitecture(architecture, out var buildApkPerCpuArchitecture);

        Yoozoo.Managers.ResourceManagement.BuildPlayer.Build(
            packagePath, channel, bundleVersion, bundleVersionCode, isDevelopmentBuild, isUpdateResource, isLog,
            resourceType, serverVersionUrl, subPackage, false, false, isExportProject, arch, buildApkPerCpuArchitecture,
            isFirstPackage,isDeepMode,isAutoProfiler);

    }

    /// <summary>
    /// 构建HybridCLR C#热更相关资源
    /// </summary>
    public static void BuildHybridCLR()
    {
        EditorSettings.cacheServerMode = CacheServerMode.Disabled;
        EditorSettings.cacheServerEnableDownload = false;
        EditorSettings.cacheServerEnableUpload = false;
        
        bool isUWALauncher = GetCMDLineArg("-UWA_Launcher") == "true";        // 是否打开UWA
        bool isGT = GetCMDLineArg("-GT") == "true"; //GT
        bool isYZPD = GetCMDLineArg("-YZPD") == "true"; //YZPD
        bool isEventTrace = GetCMDLineArg("-EventTrace") == "true";// 是否发送统计数据
        bool isUprProfiler = GetCMDLineArg("-isUprProfiler") == "true"; // 是否打开UPR
        bool isLog = GetCMDLineArg("-log") == "true"; //是否打开日志

        using (var setup = new DefineSymbolSetup())
        {
            setup.UpdateDefineSymbol("GT", isGT);
            setup.UpdateDefineSymbol("YZPD", isYZPD);
            setup.UpdateDefineSymbol("UWA", isUWALauncher);
            if (isUWALauncher)
            {
                setup.UpdateDefineSymbol("ENABLE_UWA_SDK", true);
            }
            else
            {
                setup.UpdateDefineSymbol("DISABLE_UWA_SDK", true);
            }
            setup.UpdateDefineSymbol("EventTrace", isEventTrace);
            setup.UpdateDefineSymbol("ENABLE_HYBRID_CLR", true);
            setup.UpdateDefineSymbol("DEBUG", isLog);
            setup.UpdateDefineSymbol("ENABLE_LOG", isLog);

            if (!isLog)
            {
                //开启error和warning的日志打印
                setup.UpdateDefineSymbol("ENABLE_WARNING_AND_ABOVE_LOG", true);
            }

            // 暂时没有单独的选项控制OnGUI(), 用 isLog 进行控制
            setup.UpdateDefineSymbol("ASTAR_NO_GUI", !isLog);
            setup.UpdateDefineSymbol("ENABLE_ONGUI_RUNTIME", isLog);

            // 不开启UPR的时候，启用 NO_PACKAGE， UPRTools/Scripts/PackageLoad
            setup.UpdateDefineSymbol("NO_PACKAGE", !isUprProfiler);
            if (!isUprProfiler)
            {
                // 不开启UPR的时候，移除USE_LUA,UPR_LUA_PROFILER
                setup.UpdateDefineSymbol("USE_LUA", false);
                setup.UpdateDefineSymbol("UPR_LUA_PROFILER", false);
            }
        }

        if (!isUprProfiler)
        {
            // 不开启UPR的时候，所有选项关闭，不要注入代码了
            // var setting = UPRToolSetting.Instance;
            // setting.enableMonoProfiler = false;
            // setting.loadScene = false;
            // setting.loadAsset = false;
            // setting.loadAssetBundle = false;
            // setting.instantiate = false;
            // setting.enableLuaProfiler = false;
        }

        // 修改入口场景
        EditorBuildSettings.scenes = new EditorBuildSettingsScene[]
        {
            new EditorBuildSettingsScene("Assets/Scenes/Entry.unity", true)
        };

        Plugins.ManuallyReload.ManuallyReloadSetting.Instance.IsEnableManuallyReload = false;

        // 开启HybridCLR
        HybridCLR.Editor.SettingsUtil.Enable = true;
        
        HybridCLR.Editor.Commands.PrebuildCommand.GenerateAll();

        BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
        // 打包场景
        HybridCLR.Editor.BuildAssetsCommand.BuildAssetBundleByTarget(target);
        // 复制热更DLL，metadata到输出目录，并生成版本文件
        HybridCLR.Editor.BuildAssetsCommand.CopyABAOTHotUpdateDlls(target);
    }

    private static int GetArchitecture(string architecture, out bool buildApkPerCpuArchitecture)
    {
        int arch = -1;
        buildApkPerCpuArchitecture = false;
        if (architecture == "all")
        {
            arch = (int) (AndroidArchitecture.ARM64 | AndroidArchitecture.ARMv7);
        }
        else if (architecture == "split")
        {
            arch = (int) (AndroidArchitecture.ARM64 | AndroidArchitecture.ARMv7);
            buildApkPerCpuArchitecture = true;
        }
        else if (architecture == "arm64")
        {
            arch = (int) (AndroidArchitecture.ARM64);
        }
        else if (architecture == "armv7")
        {
            arch = (int) (AndroidArchitecture.ARMv7);
        }

        Debug.Log($"-arch = {architecture}, architecture = {arch}, buildApkPerCpuArchitecture = {buildApkPerCpuArchitecture}");

        return arch;
    }

    public static string GetCMDLineArg(string name)
    {
        var args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == name && args.Length > i + 1)
            {
                return args[i + 1];
            }
        }

        return null;
    }
    /// <summary>
    /// 更新默认宏定义
    /// </summary>
    /// <param name="symbolsName">需要修改的宏名称</param>
    /// <param name="state">true：增加，false:移除</param>
    public static void UpdateDefineSymbol(string symbolsName, bool state)
    {
        if (string.IsNullOrEmpty(symbolsName))
        {
            return;
        }

        BuildTargetGroup targetGroup = BuildTargetGroup.Android;
#if UNITY_IOS
            targetGroup = BuildTargetGroup.iOS;
#elif UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
            targetGroup = BuildTargetGroup.Standalone;
#endif
        string ori = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
        List<string> defineSymbols = new List<string>(ori.Split(';'));
        bool isContains = defineSymbols.Contains(symbolsName);


        Debug.Log("UpdateDefineSymbol:" + symbolsName.ToString() + "    state:" + state.ToString() + "            isContains:" + isContains.ToString());
        if (isContains && !state)
        {
            defineSymbols.Remove(symbolsName);  //移除
            Debug.Log("移除宏：" + symbolsName);
        }
        else if (!isContains && state)
        {
            defineSymbols.Add(symbolsName);  //增加移除
            Debug.Log("新增宏：" + symbolsName);
        }

        PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defineSymbols.ToArray()));
    }

    //[MenuItem("Tools/Jenkins Support/Print Wwise SoundBankInfo")]
    public static void WwiseTest()
    {
        var xBanks = SoundBanksInfoReader.SoundBanksNode;
        if (xBanks == null)
        {
            Debug.LogError("SoundBanksInfo.xml load fails!");
            return;
        }

        string bankLoadPath = WwisePathSettings.GetBankLoadPath();

        var xFiles = SoundBanksInfoReader.StreamedFilesNode;
        int total = 0;
        foreach (var xFile in xFiles.Elements())
        {
            var id = AsScriptingHelper.GetXmlAttribute(xFile, "Id");
            var language = AsScriptingHelper.GetXmlAttribute(xFile, "Language");

            string fileName;
            if (language == "SFX")
                fileName = id + ".wem";
            else
                fileName = language + "/" + id + ".wem";

            string filePath = Path.Combine(bankLoadPath, fileName);
            if (File.Exists(filePath))
            {
                total++;
                //File.Delete(filePath);
            }
            else
            {
                Debug.LogEditorError("File not found: " + filePath);
            }
        }

        Debug.LogEditorError("total: " + total);

        int refTotal = 0;
        StringBuilder stringBuilder = new StringBuilder();
        foreach (var xBank in xBanks.Elements())
        {
            var shortName = AsScriptingHelper.GetXmlElement(xBank, "ShortName");
            var path = AsScriptingHelper.GetXmlElement(xBank, "Path");
            var language = AsScriptingHelper.GetXmlAttribute(xBank, "Language");

            if (!File.Exists(AsScriptingHelper.CombinePath(bankLoadPath, path))) 
                continue;

            var xStreams = xBank.Element("ReferencedStreamedFiles");
            if (xStreams == null) 
                continue;

            if (stringBuilder.Length > 0)
                stringBuilder.AppendLine();
            stringBuilder.AppendLine(shortName);
            foreach (var xFile in xStreams.Elements())
            {
                var fileName = AsScriptingHelper.GetXmlAttribute(xFile, "Id");
                string filePath;
                if (language == "SFX")
                    filePath = fileName + ".wem";
                else
                    filePath = language + "/" + fileName + ".wem";
                stringBuilder.AppendLine(filePath);
                refTotal++;
            }
        }
        Debug.LogEditorError(refTotal);
        Debug.LogEditorError(stringBuilder);
    }

    /// <summary>
    /// 安装Hybrid CLR
    /// </summary>
   // [MenuItem("HybridCLR/安装Hybrid CLR", false, 1)]
    public static void InstallHybridCLR()
    {
        var installer = new InstallerController();
        if (installer.HasInstalledHybridCLR())
        {
            UnityEngine.Debug.Log("HybridCLR installed.");
            return;
        }

        // 搭建环境
       // installer.InstallDefaultHybridCLR();

        // 第一次安装先跑下 Generate ALL
        //HybridCLR.Editor.SettingsUtil.Enable = true;
        //HybridCLR.Editor.Commands.PrebuildCommand.GenerateAll();
    }
}
